<!--  -->
<template>
  <div class="create-component-list">
    <!-- wrapper -->
    <div
      v-for="(item, index) in list"
      :key="index"
      class="component-item"
      @click="onItemClick(item)"
    >
      <l-text v-bind="item" />
      <StyledUploader @success="onImageUploaded" />
    </div>
  </div>
</template>
<script lang="ts">
import { defineComponent } from "vue";
import { v4 as uuidv4 } from "uuid";
import { ComponentData } from "@/store/editor";

import { TextComponentProps, imageDefaultProps } from "@/defaultProps";
import StyledUploader from "./styleUploader.vue";
import { UploadResp } from "@/extraType";
import { getImageDimensions } from "@/helper";
import { message } from "ant-design-vue";
export default defineComponent({
  name: "components-list",
  components: {
    StyledUploader,
  },
  props: {
    list: {
      type: Array,
      required: true,
    },
  },
  emits: ["on-item-click"],
  setup(props, context) {
    const onItemClick = (props: TextComponentProps) => {
      const newComponent: ComponentData = {
        id: uuidv4(),
        name: "l-text",
        props,
      };
      context.emit("on-item-click", newComponent);
    };
    const onImageUploaded = (data: { resp: UploadResp; file: File }) => {
      const { resp, file } = data;
      const componentData: ComponentData = {
        name: "l-image",
        id: uuidv4(),
        props: {
          ...imageDefaultProps,
        },
      };
      message.success("上传成功");
      componentData.props.src = resp.data.url;
      getImageDimensions(file).then(({ width }) => {
        // console.log(width)
        const maxWidth = 373;
        componentData.props.width =
          (width > maxWidth ? maxWidth : width) + "px";
        console.log(componentData);
        // 上传图片成功之后 添加到编辑器组件列表中
        context.emit("on-item-click", componentData);
      });
    };
    return {
      onItemClick,
      onImageUploaded,
    };
  },
});
</script>
<style lang="scss" scoped>
.component-item {
  width: 100px;
  margin: 0 auto;
  margin-bottom: 15px;
}
</style>